package com.example.asus.facerecognitiondemo;

import android.content.Intent;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.Paint;
import android.media.FaceDetector;
import android.net.Uri;
import android.os.Handler;
import android.os.Message;
import android.provider.MediaStore;
import android.support.annotation.Nullable;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.text.TextUtils;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;


import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

public class MainActivity extends AppCompatActivity implements View.OnClickListener {

    private ImageView mPhoto;
    private Button btnGet, btnDelect;
    private TextView btnTip;
    private View mWaitting;
    private String mCurrentPhotoStr;
    private int PICK_CODE = 1001;
    private Bitmap mPhotoImg;
    private Paint mPaint;
    private JSONObject face;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        initView();
        initClick();

        initPaint();
    }

    private void initPaint() {
        mPaint = new Paint();
    }

    private void initClick() {
        btnDelect.setOnClickListener(this);
        btnGet.setOnClickListener(this);
    }

    private void initView() {
        mPhoto = findViewById(R.id.id_photo);
        btnGet = findViewById(R.id.id_getImage);
        btnDelect = findViewById(R.id.id_detectImage);
        btnTip = findViewById(R.id.tip);
        mWaitting = findViewById(R.id.waitting);
    }

    @Override
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.id_getImage:
                Intent intent = new Intent(Intent.ACTION_PICK);
                intent.setType("image/*");
                startActivityForResult(intent, PICK_CODE);
                break;
            case R.id.id_detectImage:
                mWaitting.setVisibility(View.VISIBLE);
                DetectDemo.detect(mPhotoImg, new DetectDemo.Callback() {
                    @Override
                    public void success(JSONObject result) {
                        Log.e("msg",result.toString());
                        Message message = Message.obtain();
                        message.what = MSG_SUCCESS;
                        message.obj = result;
                        handler.sendMessage(message);
                    }

                    @Override
                    public void error(Exception exception) {
                        Message message = Message.obtain();
                        message.what = MSG_ERROE;
                        message.obj = exception.getMessage();
                        handler.sendMessage(message);
                    }
                });
                break;
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        if (requestCode == PICK_CODE) {
            if (data != null) {
                Uri uri = data.getData();
                Cursor cursor = getContentResolver().query(uri, null,
                        null, null, null);
                cursor.moveToFirst();
                int idx = cursor.getColumnIndex(MediaStore.Images.ImageColumns.DATA);
                mCurrentPhotoStr = cursor.getString(idx);
                cursor.close();

                resizePhoto();
                mPhoto.setImageBitmap(mPhotoImg);
                btnTip.setText("Click here ——>");
            }
        }
        super.onActivityResult(requestCode, resultCode, data);
    }

    private void resizePhoto() {
        BitmapFactory.Options options = new BitmapFactory.Options();
        options.inJustDecodeBounds = true;
        BitmapFactory.decodeFile(mCurrentPhotoStr, options);
        double radio = Math.max(options.outWidth * 1.0d / 1024f,
                options.outHeight * 1.0d / 1024f);
        options.inSampleSize = (int) Math.ceil(radio);
        options.inJustDecodeBounds = false;
        mPhotoImg = BitmapFactory.decodeFile(mCurrentPhotoStr, options);
    }

    private static final int MSG_SUCCESS = 1002;
    private static final int MSG_ERROE = 1003;

    private Handler handler = new Handler(new Handler.Callback() {
        @Override
        public boolean handleMessage(Message message) {
            switch (message.what) {
                case MSG_SUCCESS:
                    mWaitting.setVisibility(View.GONE);
                    JSONObject rs = (JSONObject) message.obj;

                    prepareRsBitmap(rs);

                    mPhoto.setImageBitmap(mPhotoImg);
                    break;
                case MSG_ERROE:
                    mWaitting.setVisibility(View.GONE);
                    String errorMsg = (String) message.obj;
                    if (TextUtils.isEmpty(errorMsg)) {
                        btnTip.setText("Error");
                    } else {
                        btnTip.setText(errorMsg);
                    }
                    break;
            }
            return false;
        }
    });

    private void prepareRsBitmap(JSONObject rs) {
        Bitmap bitmap = Bitmap.createBitmap(mPhotoImg.getWidth(),
                mPhotoImg.getHeight(), mPhotoImg.getConfig());
        Canvas canvas = new Canvas(bitmap);
        canvas.drawBitmap(mPhotoImg,0,0,null);

        try {
            JSONArray faces = rs.getJSONArray("faces");
            int faceCount = faces.length();
            btnTip.setText("共找到了" + faceCount + "张脸");
            for (int i = 0; i < faceCount; i++) {
                face = faces.getJSONObject(i);
                JSONObject posObj = face.getJSONObject("face_rectangle");
                JSONObject posObj2 = face.getJSONObject("attributes");

                float left = (float) posObj.getInt("left");
                float top = (float) posObj.getInt("top");
                float width = (float) posObj.getInt("width");
                float height = (float) posObj.getInt("height");



                mPaint.setColor(0xffffffff);
                mPaint.setStrokeWidth(3);

                canvas.drawLine(left,top
                ,left,top+height,mPaint);

                canvas.drawLine(left,top
                        ,left+width,top,mPaint);

                canvas.drawLine(left+width,top
                        ,left+width,top+height,mPaint);

                canvas.drawLine(left,top+height
                        ,left+width,top+height,mPaint);
                Toast.makeText(this, "你看起来"+posObj2.getJSONObject("age").getInt("value")+"岁", Toast.LENGTH_SHORT).show();
                mPhotoImg = bitmap;
            }
        } catch (JSONException e) {
            e.printStackTrace();
        }
    }
}
